//
//  PhotoImangVC.m
//  EJLX
//
//  Created by adc on 15/11/12.
//  Copyright © 2015年 江苏一键联信息科技有限公司. All rights reserved.
//

#import "PhotoImangVC.h"
#import "UserTableViewCell.h"
#import "PhotoCell.h"
#import "FootView.h"
//#import "AFNetworking.h"
#import <CsPaySDK/AFNetworking.h>
#import "CheckPeopleVC.h"
@interface PhotoImangVC ()

@end

@implementation PhotoImangVC

- (void)viewDidLoad {
    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    [super viewDidLoad];
    [self creatNav];
   
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
   collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, WIDE, HEIGHT-64) collectionViewLayout:layout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:collectionView];
    [collectionView registerNib:[UINib nibWithNibName:@"PhotoCell" bundle:nil] forCellWithReuseIdentifier:@"photo"];
      [collectionView registerNib:[UINib nibWithNibName:@"FootView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    _moRenImgArr = @[@"身份证.jpg",@"身份证反.jpg",@"银行卡.jpg",@"银行卡反.jpg",@"手持身份证.jpg",@"信用卡.jpg"];
}


//-(void)path{
//    
//    NSString *imagePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"img%d.jpg",_indexrow]];
//    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
//    self.img = savedImage;
//}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"photo" forIndexPath:indexPath];
  //  NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@""];
    cell.backgroundColor = [UIColor whiteColor];
//    NSString *imagePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"img%d.jpg",(int)indexPath.section*2+(int)indexPath.row]];
//    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSData *data =   [userDefaults objectForKey:[NSString stringWithFormat:@"imgphoto%d.jpg",(int)indexPath.section*2+(int)indexPath.row]];
    UIImage *savedImage = [UIImage imageWithData:data];
    if (!savedImage) {
       [cell.addPhotoImage setImage:[UIImage imageNamed:_moRenImgArr[indexPath.section*2+indexPath.row]]];
        }else{
            cell.addPhotoImage.image = savedImage;

    }

//    NSString *imagePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"img%d%d.jpg",indexPath.section,indexPath.row]];
//    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
//    cell.addPhotoImage.image = savedImage;
    
    return cell;
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    NSArray *titleArray = @[@"*只支持二代身份证",@"*支持绑定建行、交通、招商、工商的储蓄卡",@"*手持身份证照片必须清晰，能看清上面的文字，头像完整清晰，免冠"];
    
    FootView *reusable = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
//    UILabel *LB = (UILabel *)[reusable viewWithTag:1];
//    reusable.backgroundColor = [UIColor whiteColor];
    reusable.lable.text = titleArray[indexPath.section];
    return reusable;
}
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(WIDE, 44);
//}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((WIDE-5)/2.f-2, 120.f);
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(5, 2, 5, 2);
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(WIDE, 35);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

   
    _indexrow = indexPath.row;
    _indexSection = indexPath.section;
 
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing = YES;
    [self presentViewController:imagePicker animated:YES completion:nil];
    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [sheet addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            SHOW_ALERT(@"相机不可用");
            return ;
        }
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; //相机
        
        
    }]];
    
    [sheet addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
    
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
       
        
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:sheet animated:YES completion:nil];
    

}

-(void)creatNav{
    UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, WIDE, 44)];
    navView.backgroundColor = RGB_COLOR(0x00c49f);
    [self.view addSubview:navView];
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(10, 7, 30, 30);
    leftBtn.layer.cornerRadius = 20;
    [leftBtn setImage:[UIImage imageNamed:@"返回箭头"] forState:UIControlStateNormal] ;
    [leftBtn addTarget:self action:@selector(backBtn) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:leftBtn];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(WIDE/2-60, 7, 120, 30  )];
    title.text = @"照片";
    title.textAlignment = NSTextAlignmentCenter;
    title.textColor = [UIColor whiteColor];
    [navView addSubview:title];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(WIDE-50, 7, 30, 30);
    rightBtn.layer.cornerRadius = 20;
    [rightBtn setTitle:@"提交"  forState:UIControlStateNormal] ;
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:12.f];
    [rightBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:rightBtn];
    
}
-(void)backBtn{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)save{
    [GMDCircleLoader setOnView:self.view withTitle:@"上传中...." animated:YES];
    NSArray *array =@[@"idFront",@"idBack",@"cardBack",@"cardFront",@"idFace",@"creditCardFront"];
   
//    NSDictionary *dict =@{@"idfront":@"img.jpg",
//                          @"idBack":@"img1.jpg",
//                          @"cardBack":@"img2.jpg",
//                          @"cardFront":@"img3.jpg",
//                          @"idFace":@"img4.jpg",
//                          @"creditCardFront":@"img5.jpg",
//                          @"token":ACCESS_TOKEN
//                          
//                          };
    NSDictionary *dict =@{
                          @"token":ACCESS_TOKEN
                          
                          };
 
        AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
               manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        [manager POST:[NSString stringWithFormat:@"%@/user/pics_update",HTTPS_ID]  parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            for (int i = 0; i < 6; i++) {
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
             NSData *data =   [userDefaults objectForKey:[NSString stringWithFormat:@"imgphoto%d.jpg",i]];
            //    UIImage *img = [UIImage imageWithData:data];
                [formData appendPartWithFileData:data name:array[i] fileName:[NSString stringWithFormat:@"img%d.jpg",i] mimeType:@"image/jpeg"];
            }
          
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
           
           // NSDictionary *result = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"上传成功  ----%@",dict);
            if ([[dict objectForKey:@"errmsg"] isEqualToString:@"ok"]) {
                SHOW_ALERT(@"上传成功");
                [GMDCircleLoader hideFromView:self.view animated:YES];
//                if (self.returnBlock) {
//                      self.returnBlock(@"已完善");
//                    
//                    }
               
                [self.navigationController popViewControllerAnimated:YES];
                

            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    
            NSLog(@"上传失败　error = %@",error);
            
        }];

    
//  [HttpsManager postPersonImagesCompletion:^(int errcode, NSString *errmsg) {
//       
//        NSString*str=[NSString stringWithFormat:@"%d",errcode];
//        
//        if ([str isEqualToString:@"0"])
//        {
//            SHOW_ALERT(errmsg);
//            //_image=image;
//            //[_tabelView reloadData];
//            if (self.returnBlock) {
//                self.returnBlock(@"已完善");
//            }
//            [self.navigationController popViewControllerAnimated:YES];
//
//            return ;
//            
//        }
//        SHOW_ALERT(errmsg);
//
//    }];

    
   // [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - picker
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"])
    
    {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        //压缩图片
        
        UIImage *smallImage = [self scaleFromImage:image toWidth:350];
        
        NSData * imageData = UIImageJPEGRepresentation(smallImage, 0.5);
        
        UIImage *saveImage = [UIImage imageWithData:imageData];
        
       // self.imgView.image = saveImage;
        
        [self.imgArray addObject:saveImage];
        NSLog(@"--------imageArr==%@\n--------",self.imgArray);
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:imageData forKey:[NSString stringWithFormat:@"imgphoto%d.jpg",_indexSection*2+_indexrow]];
        [userDefaults synchronize];
        
        // 保存图片至本地，方法见下文
        [self saveImage:saveImage withName:[NSString stringWithFormat:@"img%d.jpg",_indexSection*2+_indexrow]];
        
       
    }
    [collectionView reloadData];
    [self dismissViewControllerAnimated:YES completion:nil];
    
//    self.img = info[UIImagePickerControllerOriginalImage];
//    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
//    
//        UIImageWriteToSavedPhotosAlbum(self.img, nil, nil, nil);
//        
//    }else if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){
//        
//    }
////    //输出字典，获取key值
////    
////    self.img = info[UIImagePickerControllerOriginalImage];
////    [collectionView reloadData];
////    
//    [self saveImage:self.img WithName:[NSString stringWithFormat:@"photo/%d.png",_indexrow]];
//    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//保持长宽比 固定宽度 生成小图片
- (UIImage *)scaleFromImage:(UIImage *) image toWidth:(CGFloat)width
{
    UIImage * newimage;
    
    if (image == nil) {
        
        newimage = nil;
        
    }else {
        
        CGSize oldSize = image.size;
        
        CGSize newSize;
        newSize.width = width;
        newSize.height = (oldSize.height/oldSize.width)*width;
        
        UIGraphicsBeginImageContext(newSize);
        [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    return newimage;
}
#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    
    [imageData writeToFile:fullPath atomically:NO];
}





-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [collectionView reloadData];
    [self dismissViewControllerAnimated:YES completion:nil];
}

//保存本地
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName{
    NSData *data = UIImagePNGRepresentation(tempImage);
    NSString *photoPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingString:imageName];
    [data writeToFile:photoPath atomically:YES];
    
    
}
-(NSString *)documentPath{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}
-(UIImage *)getImageFromSandBox:(NSString *)str{
    
NSData *data = [NSData dataWithContentsOfFile:[self getFilePath:str]];

UIImage *image = [UIImage imageWithData:data];

//if (image != nil)
//{
//    // 缓存到内存
//    [_allCacheDict setObject:image forKey:str];
//}

return image;
}
// 获取沙盒中缓存的图片的路径
- (NSString *)getFilePath:(NSString *)urlString
{
    NSString *directoryPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/photo"];
    
    // 保证沙盒下Documents中一定有一个ImageCache文件夹
    if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *fileName = [[urlString componentsSeparatedByString:@"/"] lastObject];
    
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",directoryPath,fileName];
    
    return filePath;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
